package com.laowang.project.system.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.framework.web.page.TableDataInfoMy;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.domain.vo.CarResultObject;
import com.laowang.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

import javax.swing.undo.CannotUndoException;

/**
 * 我的生活圈Controller
 *
 * @author laowang
 * @date 2023-04-19
 */
@Api(tags = "我的生活圈接口")
@RestController
@RequestMapping("/lifeCircle")
public class MyLifeCircleController extends BaseController {
    @Autowired
    private MyLifeCircleService myLifeCircleService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private UserPointLogService userPointLogService;

    @Autowired
    private MyLifeCircleGiftService myLifeCircleGiftService;

    @Autowired
    private MyCyhCarGroupService myCyhCarGroupService;

    /**
     * 查询我的生活圈列表
     */
    @ApiOperation(value = "小程序端 查询我的生活圈列表",notes = "")
    @GetMapping("/web/list")
    public TableDataInfoMy myLifeList(MyLifeCircle myLifeCircle) {

        List<MyCyhCarGroup> myCyhCarGroups = myCyhCarGroupService.selectMyCyhCarGroupListWeb(null);
        Map<Integer, String> collect = myCyhCarGroups.stream().collect(Collectors.toMap(MyCyhCarGroup::getId, MyCyhCarGroup::getGroupName));

        startPage();
        List<MyLifeCircle> list = myLifeCircleService.selectMyLifeCircleListWeb(myLifeCircle);
        for (MyLifeCircle lifeCircle : list) {
            List<CarResultObject> cartList = lifeCircle.getCartList();
            for (CarResultObject carResultObject : cartList) {
                String product = carResultObject.getProduct();
                //StringUtils.substringBefore()
                if (StringUtils.isNotEmpty(product)){
                    product = product.replaceAll("\\(", "").replaceAll("牌", "").replaceAll("\\s*", "").replaceAll("[^(\\u4e00-\\u9fa5)]", "");

                }
                //System.out.println(s);
                carResultObject.setProduct(product);
            }
            if (StringUtils.isNotEmpty(lifeCircle.getGroupName()) && collect.containsKey(Integer.valueOf(lifeCircle.getGroupName())) ){
                lifeCircle.setGroupName(collect.get(Integer.valueOf(lifeCircle.getGroupName())));
            }
        }
        return getDataTableMy(list);
    }

    @ApiOperation(value = "小程序端 打赏车友圈",notes = "")
    @GetMapping("/web/gifts")
    public AjaxResult gifts(Integer toUserId,Integer lifeCircleId,Integer point) {
        if (Objects.isNull(point)){
            throw new CustomException("打赏的积分不能为空",400);
        }
        if (point<=0){
            throw new CustomException("打赏的积分不能小于0",400);
        }


        MyLifeCircle myLifeCircle = myLifeCircleService.selectMyLifeCircleById(lifeCircleId);
        if (myLifeCircle == null){
            throw new CustomException("要打赏的车友圈不存在",400);
        }

        synchronized (this){
            Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
            WxUser wxUser = wxUserService.selectWxUserById(mid);
            Integer points = wxUser.getPoints();
            if (points < point){
                throw new CustomException("积分不足",400);
            }
            WxUser wxUser1 = wxUserService.selectWxUserById(toUserId);
            if (wxUser1 == null){
                throw new CustomException("被打赏的用户不存在",400);
            }

            Integer shengyu = points - point;
            wxUser.setPoints(shengyu);
            UserPointLog userPointLog = new UserPointLog();
            userPointLog.setUserId(mid);
            userPointLog.setType(5);//打赏
            userPointLog.setCreated(new Date());
            userPointLog.setOldPoint(points);
            userPointLog.setChangePoint(point);
            userPointLog.setNewPoint(shengyu);
            userPointLog.setRemark("打赏车友圈:"+lifeCircleId);

            userPointLogService.insertUserPointLog(userPointLog);
            wxUserService.updateWxUser(wxUser);// 减积分

            Integer points1 = wxUser1.getPoints();
            Integer points2 = points1 +point;
            UserPointLog userPointLog1 = new UserPointLog();
            userPointLog1.setUserId(toUserId);
            userPointLog1.setType(5);//打赏
            userPointLog1.setCreated(new Date());
            userPointLog1.setOldPoint(points1);
            userPointLog1.setChangePoint(point);
            userPointLog1.setNewPoint(points2);
            userPointLog1.setRemark("车友圈被打赏:"+lifeCircleId);

            wxUser1.setPoints(points2);
            userPointLogService.insertUserPointLog(userPointLog1);
            wxUserService.updateWxUser(wxUser1);// 加积分

            MyLifeCircleGift myLifeCircleGift = new MyLifeCircleGift();
            myLifeCircleGift.setFromUserId(mid);
            myLifeCircleGift.setToUserId(toUserId);
            myLifeCircleGift.setPoint(point);
            myLifeCircleGift.setCreated(new Date());
            myLifeCircleGift.setLifeCircleId(lifeCircleId);
            myLifeCircleGiftService.insertMyLifeCircleGift(myLifeCircleGift);

        }


        return AjaxResult.success("操作成功");
    }

    @ApiOperation(value = "小程序端 新增我的生活圈",notes = "")
    @PostMapping("/web/addLife")
    public AjaxResult addLife(@RequestBody MyLifeCircle myLifeCircle) {
        Integer i =  myLifeCircleService.addLife(myLifeCircle);
        return AjaxResult.success("操作成功",i);
    }

    @ApiOperation(value = "小程序端 查询生活圈详情",notes = "")
    @PostMapping("/web/{id}")
    public AjaxResult webId(@PathVariable Integer id) {
        return AjaxResult.success(myLifeCircleService.selectMyLifeCircleBywebId(id));
    }

    @ApiOperation(value = "小程序端 删除生活圈",notes = "")
    @PostMapping("/delete/{id}")
    public AjaxResult deleteId(@PathVariable Integer id) {
        MyLifeCircle myLifeCircle = myLifeCircleService.selectMyLifeCircleById(id);
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        if (mid.equals(12) || mid.equals(2880) ){

        }else {
            if (!myLifeCircle.getUserId().equals(mid)){
                return AjaxResult.error("作者不是自己");
            }
        }

        myLifeCircleService.deleteMyLifeCircleById(id);
        return AjaxResult.success("删除成功");
    }



    /**
     * 查询我的生活圈列表
     */
    @ApiOperation(value = "查询我的生活圈列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:circle:list')")
    @GetMapping("/list")
    public TableDataInfo list(MyLifeCircle myLifeCircle) {
        startPage();
        List<MyLifeCircle> list = myLifeCircleService.selectMyLifeCircleList(myLifeCircle);
        return getDataTable(list);
    }

    /**
     * 导出我的生活圈列表
     */
    @ApiOperation(value = "导出我的生活圈列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:circle:export')")
    @GetMapping("/export")
    public AjaxResult export(MyLifeCircle myLifeCircle) {
        List<MyLifeCircle> list = myLifeCircleService.selectMyLifeCircleList(myLifeCircle);
        ExcelUtil<MyLifeCircle> util = new ExcelUtil<MyLifeCircle>(MyLifeCircle.class);
        return util.exportExcel(list, "circle");
    }

    /**
     * 获取我的生活圈详细信息
     */
    @ApiOperation(value = "获取我的生活圈详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:circle:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myLifeCircleService.selectMyLifeCircleById(id));
    }

    /**
     * 新增我的生活圈
     */
    @ApiOperation(value = "新增我的生活圈",notes = "")
    @PreAuthorize("@ss.hasPermi('my:circle:add')")
    @PostMapping
    public AjaxResult add(@RequestBody MyLifeCircle myLifeCircle) {
        return toAjax(myLifeCircleService.insertMyLifeCircle(myLifeCircle));
    }

    /**
     * 修改我的生活圈
     */
    @ApiOperation(value = "修改我的生活圈",notes = "")
    @PreAuthorize("@ss.hasPermi('my:circle:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody MyLifeCircle myLifeCircle) {
        return toAjax(myLifeCircleService.updateMyLifeCircle(myLifeCircle));
    }

    /**
     * 删除我的生活圈
     */
    @ApiOperation(value = "删除我的生活圈",notes = "")
    @PreAuthorize("@ss.hasPermi('my:circle:remove')")
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(myLifeCircleService.deleteMyLifeCircleByIds(ids));
    }
}
